package com.app.qbake.module.square.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.qbake.R;
import com.app.qbake.H5Activity;
import com.app.qbake.module.mine.event.H5PaySuccessEvent;
import com.app.qbake.module.square.event.AddressItemClickEvent;
import com.app.qbake.module.square.layout.AddressLayout;
import com.app.qbake.module.square.layout.OrderCreateLayout;
import com.app.qbake.util.FormatUtil;
import com.wind.base.BaseActivity;
import com.wind.base.H5Param;
import com.wind.base.bean.Config;
import com.wind.base.repo.ConfigRepo;
import com.wind.base.utils.ActivityUtil;
import com.wind.base.utils.LogUtil;
import com.wind.base.utils.Navigator;
import com.wind.base.utils.ViewInflater;
import com.wind.data.mine.bean.Address;
import com.wind.data.square.OrderCreateRequest;
import com.wind.data.square.OrderCreateResponse;
import com.wind.data.square.bean.Goods;
import com.wind.pingpp.PaymentChannel;
import com.wind.pingpp.util.PaymentUtil;
import com.wind.toastlib.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailActivity extends BaseActivity {

    public static void start(Context context, Goods goods){
        Navigator.navigate(context,OrderDetailActivity.class,goods);
    }
    private Goods mGoods;
    private AddressLayout mAddressLayout;
    private OrderCreateLayout mOrderCreateLayout;
    //GOODS
    TextView tv_name,tv_goods_title,tv_price,tv_express_fee;
    ImageView iv;

    TextView tv_total_price;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        tv_name=$(R.id.tv_name);
        tv_goods_title=$(R.id.tv_goods_title);
        tv_price=$(R.id.tv_price);
        tv_express_fee=$(R.id.tv_express_fee);
        tv_total_price=$(R.id.tv_total_price);
        iv=$(R.id.iv);
        mGoods=Navigator.getSerializableExtra(this);
        ViewGroup layout_user_addr=$(R.id.layout_user_addr);
        mAddressLayout=new AddressLayout(getActivity(), layout_user_addr, new AddressLayout.OnAddressLoadListener() {
            @Override
            public void onAddressLoad(Address address) {
                mAddress=address;
            }
        });
        mAddressLayout.loadAddr();
        mOrderCreateLayout=new OrderCreateLayout(getActivity(), new OrderCreateLayout.OnChargeLoadListener() {
            @Override
            public void onChargeLoad(OrderCreateResponse response) {
                boolean pingMode=ConfigRepo.getInstance().get(getActivity()).getPing().equals(Config.PAYMODE_PING_YES);
               if (pingMode) {
                   LogUtil.e("CHARGE",response.getData().getCharge());
                   //调用pingpp
                   PaymentUtil.startPay(getActivity(), response.getData().getCharge());
               }else {
                   H5Param param=H5Param.obtain(response.getData().getCharge(),"","");
                   H5Activity.start(getActivity(),param);
               }
            }
        });

        inflateGoods();
    }

    private void inflateGoods() {
        tv_name.setText(mGoods.getUserName());
        tv_goods_title.setText(mGoods.getTitle());
        tv_price.setText("￥"+mGoods.getPrice());
        tv_express_fee.setText("￥"+mGoods.getPostage_price());
        ViewInflater.inflateImage(iv,mGoods.getImages_url().get(0));
        double total=Double.parseDouble(mGoods.getPrice())+Double.parseDouble(mGoods.getPostage_price());

        String totalPrice= FormatUtil.formatMoney(total);
        tv_total_price.setText("￥"+totalPrice);
    }

    @Override
    protected void setTitle() {
        mTitleBar.setTitle("填写订单");
    }
    private Address mAddress;
    @OnClick({R.id.tv_submit})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.tv_submit:
                if (mAddress==null){
                    ToastUtil.showToast(getActivity(),"请选择收货地址");
                    return;
                }
                OrderCreateRequest request=new OrderCreateRequest();
                request.setShop_id(mGoods.getId());
                request.setShop_userId(mGoods.getUserId());
                request.setUser_name(mAddress.getName());
                request.setUser_phone(mAddress.getPhone());
                StringBuilder addrBuilder=new StringBuilder();
                addrBuilder.append(mAddress.getProvince())
                        .append(mAddress.getCity())
                        .append(mAddress.getArea())
                        .append(mAddress.getAddress());
                request.setUser_address(addrBuilder.toString());
                request.setTitle(mGoods.getTitle());
                request.setImg_url(mGoods.getImages_url().get(0));
                request.setPrice(mGoods.getPrice());
                request.setPostage_price(mGoods.getPostage_price());
                request.setPay_code(PaymentChannel.ALIPAY.getName());
                mOrderCreateLayout.createOrder(request);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        PaymentUtil.onActivityResult(requestCode, resultCode, data, new PaymentUtil.PaymentCallback() {
            @Override
            public void onPayReturn(PaymentUtil.PaymentState state, String msg) {
                switch (state) {
                    case SUCCESS:
                        //ToastUtil.showToast(getActivity(),msg);
                        //查询一下
                        showOpLoadingIndicator();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                hideOpLoadingIndicator();
                                handlePingppSuccess();
                            }
                        },1500);


                        break;
                    case CANCEL:
                    case FAIL:
                    case INVALID:
                    case UNKNOWN:
                        hideOpLoadingIndicator();
                        ToastUtil.showToast(getActivity(), msg);
                        break;
                }
            }

        });
    }

    private void handlePingppSuccess() {
        //ToastUtil.showToast(getActivity(),"购买成功");
        GoodsBuySuccessActivity.start(getActivity(),mGoods.getCategory_id()+"");
        ActivityUtil.finish(getActivity());

        //EventBus.getDefault().post(new BuyGoodsSuccessEvent());

    }

    @Subscribe
    public void onAddressItemClickEvent(AddressItemClickEvent event){
        mAddress=event.getAddress();
        mAddressLayout.refreshAddress(mAddress);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 支付宝网页支付成功回调
     *
     * @param event
     */
    @Subscribe
    public void onH5PaySuccessEvent(H5PaySuccessEvent event) {
        handlePingppSuccess();
    }
}
